import React, { useState, useEffect } from "react";

import myImg from "../../../../assets/hoemSearch_img/my.png";
import Tinkle from "../../../../assets/hoemSearch_img/tinkle.png";
import my1Img from "../../../../assets/hoemSearch_img/my1.png";
import Tinkle1Img from "../../../../assets/hoemSearch_img/tinkle1.png";
import search from "../../../../assets/hoemSearch_img/search.png";
import userimg from '../../../../assets/hdpi/user.jpg';
import "./index.css";
import { useNavigate } from "react-router-dom";

interface UserState {
  headPic: string;
  isLoggedIn: boolean;
}

const Index: React.FC = () => {
  const [flag, setflag] = useState<boolean>(true);
  const [userInfo, setUserInfo] = useState<UserState>({
    headPic: myImg,
    isLoggedIn: false
  });
  const navigate = useNavigate()

  // 检查登录状态
  useEffect(() => {
    const users = localStorage.getItem("userInfo");
    
    if (users) {
      try {
        const parsedUserInfo = JSON.parse(users);
        setUserInfo({
          headPic: userimg, // 登录后使用固定头像
          isLoggedIn: true,
        });
      } catch (error) {
        // 解析失败，视为未登录
        setUserInfo({
          headPic: myImg,
          isLoggedIn: false,
        });
      }
    } else {
      setUserInfo({
        headPic: myImg,
        isLoggedIn: false,
      });
    }
  }, []);

  // 页面滚动
  useEffect(() => {
    // 滚动事件处理函数
    const handleScroll = () => {
      // console.log("当前滚动位置：", window.scrollY);
      if (window.scrollY < 200) {
        setflag(true);
      } else {
        setflag(false);
      }
    };

    // 添加滚动事件监听器
    window.addEventListener("scroll", handleScroll);

    // 组件卸载时移除监听器
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []); // 空依赖数组确保只运行一次

  // 处理头像点击
  const handleUserClick = () => {
    if (userInfo.isLoggedIn) {
      navigate("/user");
    } else {
      navigate("/login");
    }
  };
  return (
    <>
      <div className={flag?"topBox":"topBox flag"}>
        <img 
          src={userInfo.isLoggedIn ? userimg : (flag ? myImg : my1Img)} 
          className="userImg" 
          onClick={handleUserClick} 
          alt="" 
        />
        <div className="search_box" onClick={()=>navigate('/search')}>
          <img src={search} className="searchImg" alt="" />
          <span className="text">请输入病状/疾病</span>
          <span></span>
        </div>
        <img src={flag ? Tinkle : Tinkle1Img} className="linkleImg" alt="" />
      </div>
    </>
  );
};
export default Index;
